package chapter10.eg13;

import chapter10.eg11.Address;
import chapter10.eg11.Order;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class HttpXmlServerHandler extends SimpleChannelInboundHandler<HttpXmlRequest> {

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, HttpXmlRequest msg) throws Exception {
    FullHttpRequest request = msg.getRequest();
    Order order = (Order) msg.getBody();
    System.out.println("Http server receive request: " + order);
    doBusiness(order);
    ChannelFuture future = ctx.writeAndFlush(new HttpXmlResponse(null, order));
    if (!isKeepAlive(request)) {
      future.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
          ctx.close();
        }
      });
    }
  }

  private void doBusiness(Order order) {
    order.getCustomer().setFirstName("狄");
    order.getCustomer().setLastName("仁杰");
    order.getCustomer().setMiddleName(Collections.singletonList("李元芳"));

    Address address = order.getBillTo();
    address.setCity("洛阳");
    address.setCountry("大唐");
    address.setState("河南道");
    address.setPostCode("123456");
    order.setBillTo(address);
    order.setShipTo(address);
  }

  private boolean isKeepAlive(FullHttpRequest request) {
    return !request.headers().get(HttpHeaderNames.CONNECTION)
      .equalsIgnoreCase(HttpHeaderValues.CLOSE.toString());
  }
}
